$(document).ready(function(){
//	top_menu.lock_all();
	$(window).scrollTop(0);
	$(document).scrollTop(0);
	preload("/pics/tutorial/mr_tut.png");
	preload("/pics/circle_exclaim.png");
	preload("/pics/circle_question.png");
	tutorial_tasks_init();
	preload("/pics/tm_coin_small.png");
	preload("/pics/tm_coin_big.png");
	preload("/pics/tutorial/arrow.png");
});
var tasks_pagecontent = {};
function tutorial_tasks_init()
{
	$.post("/ajax/tutorial_tasks.ajax.php",{"type":"init","page":PAGE,"tut_done":SESSION.tutorial_done},function(data){
		if(data != null)
		{
			tasks_pagecontent = data["pagecontent"];
			if(data["hide"]) return false;
			var $mr_tut = $("<div />").addClass("mr_tut").tooltip(data["mr_tut_tooltip"]);
			var $speech = $("<div />").addClass("speech").append( $("<div />").addClass("speech_triangle") ).append($("<div>").addClass("speech_text"));
			if($("#tutorial_tasks").length > 0)
			{ // Home page
				if($(".mr_tut_box").length == 0)
				{
					var $html = $("<div />").addClass("mr_tut_box").append(	$mr_tut,$speech,$("<a />").attr("id","mr_tut_box"));
					$("#tutorial_tasks").append($html);
				}
			}
			else
			{ // Other pages
				if($(".mr_tut_over_box").length == 0)
				{
					var $mr_tut_holder = $("<div />").addClass("text_center").css("display", "inline-block").append(
						$mr_tut
					)
					var $html = $("<div />").addClass("mr_tut_over_box").append($mr_tut_holder,$speech,$("<a />").attr("id","mr_tut_box"));
					var $box = $("<div />").addClass("main_center").append($("<div />").css({"padding": "5px 80px 0px 80px"}).html($html));
					$("#top_menu_sub, .banner_top").last().after($box);
				}
			}
			var task = data["task"];
			var list_callback = function()
			{
				var $d = $("<table />").appendTo(".speech_text").css("margin-top","10px").addClass("padding task_list");
				var completed_task = null;
				for(var i in task["list"])
				{
					var t = task["list"][i];
					if(!t["time"])
					{
					var $tr = 	$("<tr />").append(
							$("<td />").addClass("task_item "+t["type"]).css({"padding-left":"22px"}),
							$("<td />").text(t["name"]).addClass("task_name"),
							$("<td/>").addClass("align_right").append(
									(t["money"]>0 ?money_big(t["money"]): ""),
									(t["pro"]>0 ?t["pro"]+' <img src="/pics/pro_icon.png" class="pro_icon" />': "")
								),
							$("<td />").html(make_button(global_content["start"],"start_task("+t["id"]+")","")).addClass("align_center start_button")
						);
					$d.append($tr); 
					}
					else{
						completed_task = t;
					}	
				}
				if(completed_task)
				{
					$("<div>").addClass("subtle align_center small completed_task").html(tasks_pagecontent[196]+" <em>"+completed_task["name"]+"</em> - "+data["completed_count"]+"/"+data["max_count"]+" "+tasks_pagecontent[197]).appendTo(".speech_text");
				}
			}
			if(task["type"] == "list")
			{
				$(".speech_text").html("");
				type_in(".speech_text",task["text"],null,list_callback);
				type_in_finish(".speech_text");
			}
			else
			{
				show_task(task);
			}
//			$(".reset_link").remove();
//			$(".mr_tut_box").append("<span class='reset_link'><br /><span onclick='reset_tasks()' class='faux_link'>reset</span> / <span onclick='complete_questions()' class='faux_link'>questions</span></span>");
//			$(".mr_tut_over_box").append("<span class='reset_link'><br /><span onclick='reset_tasks()' class='faux_link'>reset</span> / <span onclick='complete_questions()' class='faux_link'>questions</span></span>");
			// Focus on top
//			setTimeout(function(){$(document).scrollTop(0);},1000);
			if(SESSION.tutorial_done && data.tutorial_done_text)
			{ // first task popup
				SESSION.tutorial_done=0;
				var tut_text = data.tutorial_done_text;
				var first_task = task.list[0];
				var $mod = $("<div />").append(
					$("<h2 />").html(tut_text[0]),
					$("<p />").html(tut_text[1]),
					$("<p />").html(tut_text[2]),
					$("<hr />"),
					$("<p />").html(tut_text[3]+" <span class='bold'>"+first_task.name+"</span>"),
					$("<p />").html(tut_text[4]),
					$("<div />").addClass("msgbuttons").append(
						make_button(global_content.start,"start_task("+first_task.id+");modal.hide();add_arrow_to_element('.mr_tut_box','down');"),
						make_button(tut_text[5],"modal.hide();add_arrow_to_element('.mr_tut_box','down');")
						)
					);
				modal.html($mod).show();
			}
		}
	},"json");
}

function start_task(task_id)
{
	$.post("/ajax/tutorial_tasks.ajax.php",{"type":"start_task","task_id":task_id},function(data){
		if(data != null)
		{
			if(data["success"]) show_task(data["task"]);
			else
			{

			}
		}
	},"json");
}
// Cancel current task, and save it for later
function task_dismiss()
{
	$.post("/ajax/tutorial_tasks.ajax.php",{"type":"dismiss_task"},function(data){
		if(data != null)
		{
			if(data["success"])
			{
				if(PAGE == "home.php") tutorial_tasks_init();
				else page_refresh();
			}
			else
			{

			}
		}
	},"json");
}
function show_task(task)
{
	var text = "<div class='task_header "+task["type"]+"'><span class='subtle'>#"+task["task_number"]+"</span> "+task["name"]+"</div>";
	text +=task["text"];
	if(task["type"] == "question")
	{ // QUESTION
		text+="<ul class='radio_buttons' id='task_question_radio'>";
		for(var i=0;i<task["answers"].length;i++)
		{
			text+="<li class='radio less_space' radio_val='"+i+"' tabindex='"+(100+i)+"' id='question_radio"+i+"'><div class='radio_img'></div><div class='radio_label hover_text'>"+task["answers"][i]+"</div></li>";
		}
		text+="</ul>";
	}
	else
	{ // TASK
	}
	var text_callback = function()
	{
		make_radio("task_question_radio");
		if(task["type"] == "question")
		{ // Append answer buttons
			var user_guide_link = task["user_guide_link"] ? "<div class='user_guide_link'>"+pc_replace(tasks_pagecontent[198],{"[link]":"<a href='"+task["user_guide_link"]+"'>","[/link]":"</a>"})+"</div>" : "";
			$(".speech_text").append($("<div />").addClass("align_center").css({"padding-top":"5px"}).append(
				$(make_button(tasks_pagecontent[207],"task_submit_answer()")).css("width","150px").addClass("wide_button"),
				$(user_guide_link)
				)
			).find(".wide_button .button_border").css({"width":"148px","padding":"0"});
		}
		else
		{ // More tasks button
			add_more_tasks_button(task);
		}
		if(task["button"])
		{
			$(".speech_text").append("<div class='align_center'>"+make_button(task["button"]["name"],task["button"]["click"])+"</div>");
		}
		if(task["step"] == 0)
		{ // task not complete/answered, show the dismiss red x
			$(".speech_text").prepend($("<span />").css({"background":" url(/pics/small_red_x.png) no-repeat center","display":"inline-block","width":"10px","height":"10px","cursor":"pointer"}).addClass("float_right").click(function(){task_dismiss()}).tooltip(tasks_pagecontent[199]));
		}
		else
		{
			// flying fun
			if(task["pro"] > 0) rain_pro(task["pro"]);
			if(task["money"] > 0) rain_money(task["money"]);
		}
	}
	if(task["complete"])
	{
		var pro_text = task["pro"] > 0 ? "<span id='pro_rain'>"+task["pro"]+' <img src="/pics/pro_icon.png" class="pro_icon" /></span>' : "";
		var money_text = task["money"] > 0 ? "<span id='money_rain'>"+money(task["money"])+"</span>" : "";
		text += "<br /><br /><span>"+pc_replace(tasks_pagecontent[200],{"[award]":money_text+" "+pro_text})+"</span>";
	}
	$(".speech_text").html("");
	type_in(".speech_text",text,null,text_callback);
	if(task["dont_typein"]) type_in_finish(".speech_text");
}

function task_submit_answer()
{
	var answer = $("#task_question_radio").attr("radio_val");
	if(!answer)
	{
		$(".speech_text .error").remove();
		$("#task_question_radio").after($("<p />").addClass("error").text(tasks_pagecontent[201]));
//		console.log("no answer");
		return false;
	}
	$.post("/ajax/tutorial_tasks.ajax.php",{"type":"answer_question","answer":answer},function(data){
		if(data != null)
		{
			$(".speech_text").html($("<div />").addClass("task_header question").html("<span class='subtle'>#"+data["task"]["task_number"]+"</span> "+data["task"]["name"]));
			if(data["response"])
			{
				var pro_text = data["pro"] > 0 ? "<span id='pro_rain'>"+data["pro"]+' <img src="/pics/pro_icon.png" class="pro_icon" /></span>' : "";
				var money_text = data["money"] > 0 ? "<span id='money_rain'>"+money_big(data["money"])+"</span>" : "";
//				var text = "The answer is <span class='success'>CORRECT</span><br /><br /><span class='large'>"+data["correct_answer"]+"</span><br /><br />You get "+money_text+" "+pro_text+"";
				var text = "<div class='question_response'><span class='success large'>"+tasks_pagecontent[202]+"</span></div>";
				var award_text = pc_replace(tasks_pagecontent[200],{"[award]":money_text+" "+pro_text});//"You get "+money_text+" "+pro_text+"";
				var flying_fun = true;
			}
			else
			{
				var text = "<div class='question_response'><strong class='error large'>"+tasks_pagecontent[203]+"</strong></div>";
				var award_text = "";
			}
			text += "<div class='answered_question'>"+data["task"]["text"]+"</div>";
			text += "<div class='correct_answer large'>"+data["task"]["answer"]+"</div>";
			text += award_text;
//			$(".speech_text").html("");
			type_in(".speech_text",text,null,function(){
				// More tasks button
				add_more_tasks_button(data);
				if(data["pro"] > 0) rain_pro(data["pro"]);
				if(data["money"] > 0) rain_money(data["money"]);
			});
		}
	},"json");
}

function add_more_tasks_button(task)
{
	if(task["complete"]) // AND NOT LAST TASK
	{ // Show more tasks button
		$(".speech_text").append($("<div />").addClass("align_right").css({"padding-top":"5px"}).append(
			$("<span>").addClass("red_button").css({"display":"inline-block","text-align":"center"}).text(tasks_pagecontent[204]).attr("onclick","window.location='/home/'")
			)
		);
	}
}

function tutorial_tasks_show_info()
{
	var text = "<span onclick='tutorial_tasks_hide_info();' class='faux_link float_right'><img src='/pics/small_red_x.png' /></span>"
		+ tasks_pagecontent[195];
	type_in_stop(".speech_text");
	$(".speech_text").html("");
	setTimeout(function(){
		$(".speech_text").attr("stop_appending","").html("");
		type_in(".speech_text",text,null,function(){
			$(".speech_text").append("<div class='align_left'><span class='arrow_left faux_link' onclick='tutorial_tasks_hide_info()'>"+global_content["back"]+"</span></div>");
		});
	},200);
}
function tutorial_tasks_hide_info()
{
	tutorial_tasks_init();
}

function reset_tasks()
{
	$.post("/ajax/tutorial_tasks.ajax.php",{"type":"reset"},function(data)
	{
		if(data != null)
		{
			window.location = "/home/";
		}
	},"json");
}
function complete_questions()
{
	$.post("/ajax/tutorial_tasks.ajax.php",{"type":"complete_q"},function(data)
	{
		if(data != null)
		{
			window.location = "/home/";
		}
	},"json");
}





// ** Types in text to a an element ** //
// - Element is jquery-grabable element e.g. #text
// - text is a string
// - speed is ms between each char
// - callback will be called when typein is done
function type_in(element,text,speed,callback)
{
	if(!text) return false;
	$(element).click(function(){
		type_in_stop($(this));
		$(this).html($("<div>").html(text));
	});
	var text_copy = text;
	speed = speed || 10;
	var regx = /\<.+?\>/;
	var regexps = [];
	i=0;
	while(regx.test(text_copy) && i< 1000)
	{
		var rep = regx.exec(text_copy);
		text_copy = text_copy.replace(rep,"["+i+"]");
		regexps[i] = rep[0];
		i++;
	}
	var text2 = [];
	var k = 0;

	for(var i=0;i<regexps.length;i++)
	{
		var tmp = text_copy.split("["+i+"]",2);
		tmp[0] = tmp[0].split("");
		for(var j=0;j<tmp[0].length;j++)
		{
			text2[k++] = tmp[0][j];
		}
		text2[k++] = regexps[i];
		text_copy = tmp[1]+"";
	}
	tmp = text_copy.split("");
	for(var j=0;j<tmp.length;j++)
	{
		text2[k++] = tmp[j];
	}
	type_in_char(element,text2,0,speed,callback);
	// IE CRAP
	if($.browser.msie && $.browser.version < 9) type_in_finish(element);
}
function type_in_stop(element)
{
	$(element).attr("stop_appending",true);
}
function type_in_finish(element)
{
	$(element).click();
}
function type_in_char(element,chars,num,delay,callback,nest)
{
	nest = nest || [];
	if(chars[num] && $(element).attr("stop_appending") !== "true")
	{
		if(nest[0])
		{
			var $el = nest[nest.length-1];
			var tag = $el.get(0).tagName;
			if(chars[num].toLowerCase() == "</"+tag.toLowerCase()+">")
			{ // chars[num] == close-tag, so do nothing
				nest.splice(nest.length-1,1);
				setTimeout(function(){type_in_char(element,chars,num+1,delay,callback,nest)},delay);
			}
			else
			{
				if(/\<.+?\>/.test(chars[num]))
				{
					if(/.+?\/>/.test(chars[num]))
					{
						$el.append(chars[num]);
						setTimeout(function(){type_in_char(element,chars,num+1,delay,callback,nest)},delay);
					}
					else
					{
						var $t = $(chars[num]);
						$el.append($t);
						nest[nest.length]=$t;
						setTimeout(function(){type_in_char(element,chars,num+1,delay,callback,nest)},delay);
					}
				}
				else
				{
					$el.append(chars[num]);
					setTimeout(function(){type_in_char(element,chars,num+1,delay,callback,nest)},delay);
				}
			}
		}
		else if(/\<.+?\>/.test(chars[num]))
		{
			if(/.+?\/>/.test(chars[num]))
			{
				$(element).append(chars[num]);
				setTimeout(function(){type_in_char(element,chars,num+1,delay,callback)},delay);
			}
			else
			{
				var $t = $(chars[num]);
				$(element).append($t);
				setTimeout(function(){type_in_char(element,chars,num+1,delay,callback,[$t])},delay);
			}
		}
		else
		{
			$(element).append(chars[num]);
			setTimeout(function(){type_in_char(element,chars,num+1,delay,callback)},delay);
		}
	}
	else
	{
		if(typeof callback == "function")
		{
			callback.call(this);
			$(element).unbind("click");
			$(element).attr("stop_appending","");
		}
	}
}
function rain_money(money)
{
//	console.log(money);
	money = parseInt(money / 20000);
	sprite_stack_move("#money_rain", ".top_user_info .cash_block", "big_coin", money, function() {
		money_tick = parseInt($(".top_user_info .cash_block").text().replace(/,/g,""));
		$(".top_user_info .cash_block").text(number_format(money_tick+=20000));
	})

}
function rain_pro(pro)
{
	sprite_stack_move("#pro_rain", ".top_user_info .pro_days", "pro_sprite", pro, function() {
		var prodays = $(".top_user_info .pro_days").text();
		$(".top_user_info .pro_days").text(++prodays);
	})
}

function sprite_stack_move(from_element, target_element, add_class, sprite_count, callback) {
	from_element = $(from_element).first();
	target_element = $(target_element).first();

	if(from_element.length == 0) return false;

	var iterator = 0;
	function make_sprite() {

		// Make sprite, append to get dimensions
		var sprite = $("<div>").addClass(add_class).appendTo($("body"));

		if(from_element == null) return false;
		var new_top = from_element.offset().top-$(document).scrollTop()+Math.random()*30-15;
		var new_left = from_element.offset().left+$(document).scrollLeft()+Math.random()*30-15;

		sprite.css("top",new_top);
		sprite.css("left",new_left);

		sprite.animate(
		{
			"top":target_element.offset().top-$(document).scrollTop(),
			"left":target_element.offset().left+target_element.width()/2
		},
		{
			"duration": 1000,
			"specialEasing": {
				"top": 'easeInSine',
				"left": 'easeOutSine'
			},
			"complete": function() {
				callback();
				$(this).remove();
			}
		});

		// Spawn more sprites!
		if (++iterator < sprite_count) {
			setTimeout(make_sprite, 50);
		}

	}

	// Set spawning in motion
	make_sprite();

}
